<template>
  <div>
    <div class="all" v-show="!dialogVisible">
      <!-- 搜索框 -->
      <div class="search_box">
        <div>
          <div class="search_title">标题</div>
          <div>
            <el-input v-model="input" class="inputs" placeholder="请输入标题" />
          </div>
        </div>
        <div class="search_righ">
          <div class="search_title">浏览量</div>
          <el-input v-model="inputMin" class="numweek" placeholder="请输入最小浏览量" type="number" />
          <span style="margin: 0 10px">至</span>
          <el-input v-model="inputMax" class="numweek" placeholder="请输入最大浏览量" type="number" />
        </div>
      </div>
      <div class="line"></div>
      <div class="button_box">
        <el-button type="primary" class="butten" @click="adds()">新增</el-button>
        <el-button type="danger" class="butten" @click="deleteSelectedRows">批量删除</el-button>
      </div>
      <div class="table_box">
        <el-table :data="paginatedData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" width="120" align="center">
            <template #default="scope">{{ scope.row.id }}</template>
          </el-table-column>
          <el-table-column property="title" label="标题" width="200" align="center" show-overflow-tooltip />
          <el-table-column property="status" label="类型" align="center" show-overflow-tooltip />
          <el-table-column property="address" label="图片" align="center">
            <template #default="scope">
              <el-image style="width: 60px; height: 60px" :src="url + scope.row.img" :zoom-rate="1.2" :max-scale="7"
                :min-scale="0.2" :preview-src-list="[url + scope.row.img]" :initial-index="4" fit="cover" />
            </template>
          </el-table-column>
          <el-table-column property="intr" label="介绍" align="center" show-overflow-tooltip />
          <el-table-column property="quantity" label="浏览量" align="center" />
          <el-table-column property="address" label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" @click="edit(scope.row)" text>编辑</el-button>
              <el-button type="danger" @click="deletes(scope.row.id)" text>删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="demo-pagination-block">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <div class="windows" v-show="dialogVisible">
      <div class="windows_box">
        <div class="windows_title">添加/编辑</div>
        <div class="line"></div>

        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" class="form-container">
          <div class="windows_content">
            <div class="content_left">
              <el-form-item label="创业标题" prop="title">
                <el-input v-model="ruleForm.title" class="seek" placeholder="请输入标题" />
              </el-form-item>
              <el-form-item label="创业分类" prop="status">
                <el-select v-model="ruleForm.status" class="seek" placeholder="请选择分类"
                  @change="handleStatusChange">
                  <el-option label="请选择" value="" disabled></el-option>
                  <el-option label="创业" value="1"></el-option>
                  <el-option label="就业" value="2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="创业介绍" prop="intr">
                <el-input v-model="ruleForm.intr" type="textarea" max="150" class="seek"
                  placeholder="请输入介绍" />
              </el-form-item>
            </div>
            <div class="content_right">
              <el-form-item label="浏览量" prop="quantity">
                <el-input-number v-model="ruleForm.quantity" style="margin-left: 1em;" :min="1"
                  @change="handleChange" />
              </el-form-item>
              <el-form-item label="发布时间" prop="jobc_time">
                <el-date-picker v-model="ruleForm.jobc_time" type="date" placeholder="请选择日期" class="seek"
                  format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
              </el-form-item>
              <el-form-item label="创业海报" prop="img">
                <el-upload class="avatar-uploader" :file-list="fileList" v-model="ruleForm.img" list-type="picture-card"
                  :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                  :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                  <el-icon class="avatar-uploader-icon">
                    <Plus />
                  </el-icon>
                </el-upload>
              </el-form-item>
            </div>
          </div>
          <div class="UEditors">
            <el-form-item label="创业文章内容" prop="content" class="texts">
              <UEditor v-if="dialogVisible" v-model="ruleForm.content" />
            </el-form-item>
          </div>
          <div class="windows_content_box">
            <el-form-item>
              <el-button type="primary" @click="submitForm(ruleFormRef)">
                确定
              </el-button>
              <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="business">
import { ElMessage, ElMessageBox } from "element-plus";
import { reactive, onMounted, ref, watch, nextTick} from "vue";
import { url } from "/@/api/url"
import { articleGet, articleAdd, articleDel } from "/@/api/article";
import "/src/css/business.css";
import UEditor from "../../components/UEeditor/index.vue";
import axios from "axios";
import { Plus, UploadRawFile, UploadUserFile } from "@element-plus/icons-vue";

// 删除的数据id
const delid = ref([]);
// 图片上传
const fileList = ref<UploadUserFile[]>([]);
// 图片上传
const handleRemove = (file: UploadUserFile) => {
  console.log(file);
  fileList.value = [];
  ruleForm.img = "";
};
// 图片上传成功
let edit_add = ref(false);
// 图片上传成功
const imageUrl = ref<string>("");// 图片预览
// 图片上传成功
const handleAvatarSuccess = (
  response: any,
  uploadFile: UploadRawFile,
  fileList: UploadUserFile[]
) => {
  console.log(response);
  imageUrl.value = URL.createObjectURL(uploadFile.raw);
};
// 图片上传限制
const beforeAvatarUpload = (rawFile: File) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  const form = new FormData();
  form.append("file", rawFile);
  axios({
    url: "/pc/common/upload",
    method: "POST",
    data: form,
  }).then((res) => {
    console.log(res);
    console.log(1);
    ruleForm.img = res.data.data.url;
    console.log(ruleForm.img);

    fileList.value = [
      {
        name: "food.jpeg",
        url: url + res.data.data.url,
      },
    ];
  });
  return false;
};
const data = ref(null);// 数据源
const filteredData = ref([]); // 用于存储过滤后的数据
const paginatedData = ref([]); // 用于存储分页后的数据
// 标题搜索
const input = ref("");
// 浏览量搜索
const inputMax = ref("");
const inputMin = ref("");

// 分页相关变量
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
let imgUrl = ref("");

// 定义合法的下拉框选项值
const validStatusValues = ref([1, 2]);

// 控制表单是否已初始化
const formInitialized = ref(false);

// 表单数据
const ruleForm = reactive({
  title: "",
  status: "", // 初始值可以为空字符串或默认值
  content: "",
  img: " ",
  intr: "",
  quantity: "0",
  jobc_time: "",
  id: "",
});
const selectedRows = ref([]);// 用于存储选中的行数据

// 编辑弹窗
function edit(row: any) {
  edit_add.value = false;
  ruleForm.id = row.id;
  ruleForm.img = row.img;
  row.status = row.status === "创业" ? "1" :"2";
  ruleForm.status = row.status;

  dialogVisible.value = true;
  Object.assign(ruleForm, row); // 使用 Object.assign 来复制对象属性
  console.log(row);
  console.log(ruleForm);

  // 确保 jobc_time 格式为 YYYY-MM-DD
  if (ruleForm.jobc_time) {
    ruleForm.jobc_time = new Date(ruleForm.jobc_time).toISOString().slice(0, 10);
  }

  // 确保 img 回显
  if (ruleForm.img) {
    imgUrl = ruleForm.img;
    fileList.value = [
      {
        name: "创业海报",
        url: url + ruleForm.img,
      },
    ];
  } else {
    fileList.value = [];
  }

  // 重置表单初始化状态
  formInitialized.value = false;
  nextTick(() => {
    formInitialized.value = true;
  });
}

// 表单验证规则优化
const rules = reactive({
  title: [{ required: true, message: "请输入创业标题", trigger: "blur" }],
  content: [{ required: true, message: "请输入创业内容", trigger: "blur" }],
  intr: [{ required: true, message: "请输入创业简介", trigger: "blur" }],
  jobc_time: [{ required: true, message: "请输入创业时间", trigger: "blur" }],
  quantity: [{ required: true, message: "请输入创业数量", trigger: "blur" }],
  status: [
    { required: true, message: "请选择创业分类", trigger: ["blur"] },
    {
      validator: (rule: any, value: any, callback: any) => {
        // 表单未初始化时跳过验证
        if (!formInitialized.value) return callback();

        if (!value) {
          callback(new Error("请选择创业分类"));
          return;
        }
        callback()
      },
      trigger: "change"
    }
  ],
  img: [{ required: true, message: "请上传创业图片", trigger: "blur" }],
});

// 表单引用
const ruleFormRef = ref();
let dialogVisible = ref(false);

// 处理下拉框值变化
const handleStatusChange = (value: any) => {
  console.log("选择的分类值:", value);
};

onMounted(() => {
  // 获取数据
  renders()
});
// 渲染数据
const renders = () => {
  articleGet().then((res) => {
    console.log(res);
    for (let i = 0; i < res.data[0].length; i++) {
      res.data[0][i].status == 1
        ? (res.data[0][i].status = "创业")
        : (res.data[0][i].status = "就业");
    }
    const transformedData = res.data[0].map((item: any) => ({
      ...item,
    }));
    data.value = transformedData;
    filteredData.value = transformedData; // 初始化过滤后的数据
    total.value = transformedData.length;
    updatePaginatedData();
    console.log(data.value);
  });
};

// 删除
const deletes = (id: any) => {
  ElMessageBox.confirm("确定要删除此条记录吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      articleDel({ ids: id })
        .then((res) => {
          console.log(res);
          if (res.code == 1) {
            ElMessage.success("删除成功");
            renders();
          }
        })
        .catch((error) => {
          ElMessage.error("删除失败：" + error.message);
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 删除选中数据 批量删除
const deleteSelectedRows = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的记录");
    return;
  }

  ElMessageBox.confirm("确定要删除选中的记录吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const ids = selectedRows.value.join(",");
      articleDel({ ids: ids })
        .then((res) => {
          if (res.code == 1) {
            ElMessage.success("删除成功");
            // 确保 data.value 不为 null
            if (Array.isArray(data.value)) {
              total.value = data.value.length;
            } else {
              total.value = 0;
            }
            updatePaginatedData();
          }
        })
        .catch((error) => {
          ElMessage.error("删除失败：" + error.message);
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 选择框变化事件
const handleSelectionChange = (rows: any[]) => {
  // 清空 delid 数组
  delid.value = [];
  for (let i = 0; i < rows.length; i++) {
    delid.value.push(rows[i].id);
  }
  console.log(delid.value);
  selectedRows.value = delid.value;
};
// 筛选数据
function filterData() {
  if (!data.value) return;

  // 验证输入值
  const minValue = inputMin.value ? parseInt(inputMin.value) : null;
  const maxValue = inputMax.value ? parseInt(inputMax.value) : null;

  if (minValue !== null && maxValue !== null && minValue > maxValue) {
    ElMessage.warning('最小浏览量不能大于最大浏览量');
    return; // 阻止过滤操作
  }

  let filtered = data.value.filter((item: any) => {
    const titleMatch = item.title.includes(input.value);
    const quantityMatch =
      (!minValue || item.quantity >= minValue) &&
      (!maxValue || item.quantity <= maxValue);
    return titleMatch && quantityMatch;
  });

  filteredData.value = filtered;
  total.value = filtered.length;
  currentPage.value = 1; // 重置当前页码
  updatePaginatedData();
}

// 监听输入变化并调用搜索方法
watch([input, inputMax, inputMin], () => {
  filterData();
});

// 点击新增
const adds = () => {
  edit_add.value = true;
  ruleForm.id = "";
  dialogVisible.value = true;
  // 重置表单数据
  ruleForm.title = "";
  ruleForm.jobc_time = "";
  ruleForm.quantity = "";
  ruleForm.status = "";
  ruleForm.img = "";
  ruleForm.content = "";
  ruleForm.intr = "";
  fileList.value = "";  ruleForm.status = " ";

  // 重置表单初始化状态
  formInitialized.value = false;
  nextTick(() => {
    formInitialized.value = true;
  });
};

// 更新分页后的数据
function updatePaginatedData() {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  paginatedData.value = filteredData.value.slice(start, end);
}

// 处理分页事件
function handleSizeChange(newPageSize: number) {
  pageSize.value = newPageSize;
  currentPage.value = 1; // 重置当前页码
  updatePaginatedData();
}
// 处理页码变化
function handleCurrentChange(newCurrentPage: number) {
  currentPage.value = newCurrentPage;
  updatePaginatedData();
}

// 提交表单时的额外验证
function submitForm(formEl: any) {
  if (!formEl) return;

  // 确保提交时表单处于已初始化状态
  formInitialized.value = true;

  formEl.validate((valid: boolean) => {
    if (valid) {
      // 验证通过，处理提交
      articleAdd(ruleForm).then((res) => {
        console.log(res);
        if (res.code == 1) {
          dialogVisible.value = false;
        }
        ElMessage.success("提交成功!");
        articleGet().then((res) => {
          for (let i = 0; i < res.data[0].length; i++) {
            res.data[0][i].status == 1
              ? (res.data[0][i].status = "创业")
              : (res.data[0][i].status = "就业");
          }
          const transformedData = res.data[0].map((item: any) => ({
            ...item,
          }));
          data.value = transformedData;
          filteredData.value = transformedData; // 初始化过滤后的数据
          total.value = transformedData.length;
          updatePaginatedData();
        });
      });

      dialogVisible.value = false;
      console.log("提交的表单数据:", ruleForm);
    } else {
      // 验证失败，聚焦到第一个错误字段
      const firstErrorField = formEl.errors?.[0]?.field;
      if (firstErrorField === 'status') {
        ElMessage.error("请选择有效的创业分类");
      }
      return false;
    }
  });
}

// 重置表单
function resetForm(formEl: any) {
  dialogVisible.value = false;
  if (!formEl) return;
  formEl.resetFields();
}

// 处理浏览量变化
const handleChange = (value: any) => {
  console.log('浏览量变化:', value);
};

// 图片预览
const handlePictureCardPreview = (file: UploadUserFile) => {
  console.log('预览图片:', file);
};
</script>

<style scoped>
.demo-image__error .image-slot {
  font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}

.inputs {
  width: 240px;
  height: 30px
}

/* 自定义表单验证样式 */
.el-form-item.is-error .el-input__inner,
.el-form-item.is-error .el-input__inner:focus,
.el-form-item.is-error .el-textarea__inner,
.el-form-item.is-error .el-textarea__inner:focus {
  border-color: #f56c6c;
}

.el-form-item__error {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  position: absolute;
  top: 100%;
  left: 0;
}

/* 新增：表单初始化控制样式 */
.form-container:not(.form-initialized) .el-form-item__error {
  display: none !important;
}

/* 表单初始化后显示错误提示 */
.form-container.form-initialized .el-form-item__error {
  display: block;
}
</style>

<style lang="scss">
.el-table .el-table__cell.is-center {
  position: unset !important;
}
</style>